# -*- coding: utf-8 -*-
"""
Word导出器
"""
from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml.shared import OxmlElement, qn
from typing import Dict
import os
from .base_exporter import BaseExporter

class WordExporter(BaseExporter):
    """Word导出器"""
    
    def export(self, dict_data: Dict, file_path: str) -> bool:
        """
        导出为Word格式
        
        Args:
            dict_data: 数据库字典数据
            file_path: 导出文件路径
            
        Returns:
            导出是否成功
        """
        try:
            if not self._validate_file_path(file_path):
                return False
            
            # 创建文档
            doc = Document()
            
            # 设置文档样式
            self._setup_document_styles(doc)
            
            # 添加标题
            self._add_title(doc, dict_data)
            
            if self.check_cancel():
                return False
            
            # 添加摘要信息
            self._add_summary(doc, dict_data)
            
            if self.check_cancel():
                return False
            
            # 添加表结构信息
            tables = dict_data.get('tables', [])
            total_tables = len(tables)
            
            for i, table in enumerate(tables):
                if self.check_cancel():
                    return False
                
                self._add_table_section(doc, table)
                
                # 更新进度
                progress = int((i + 1) / total_tables * 100)
                self.update_progress(progress, f"正在导出表: {table['name']}")
            
            # 保存文档
            doc.save(file_path)
            return True
            
        except Exception as e:
            print(f"Word导出失败: {e}")
            return False
    
    def _setup_document_styles(self, doc: Document):
        """设置文档样式"""
        # 设置默认字体
        style = doc.styles['Normal']
        font = style.font
        font.name = '宋体'
        font.size = Pt(10.5)
        
        # 设置标题样式
        heading_style = doc.styles['Heading 1']
        heading_font = heading_style.font
        heading_font.name = '黑体'
        heading_font.size = Pt(16)
        heading_font.bold = True
    
    def _add_title(self, doc: Document, dict_data: Dict):
        """添加文档标题"""
        title = doc.add_heading('MySQL数据库字典', 0)
        title.alignment = WD_ALIGN_PARAGRAPH.CENTER
        
        # 添加数据库信息
        db_info = dict_data.get('database_info', {})
        if db_info:
            db_name = db_info.get('database_name', '')
            if db_name:
                subtitle = doc.add_heading(f'数据库: {db_name}', level=1)
                subtitle.alignment = WD_ALIGN_PARAGRAPH.CENTER
    
    def _add_summary(self, doc: Document, dict_data: Dict):
        """添加摘要信息"""
        doc.add_heading('数据库摘要', level=1)
        
        summary = self._get_export_summary(dict_data)
        db_info = dict_data.get('database_info', {})
        
        # 创建摘要表格
        table = doc.add_table(rows=1, cols=2)
        table.style = 'Table Grid'
        table.alignment = WD_TABLE_ALIGNMENT.CENTER
        
        # 设置表头
        hdr_cells = table.rows[0].cells
        hdr_cells[0].text = '项目'
        hdr_cells[1].text = '值'
        
        # 设置表头样式
        for cell in hdr_cells:
            cell.paragraphs[0].runs[0].font.bold = True
            cell.paragraphs[0].runs[0].font.name = '黑体'
        
        # 添加摘要数据
        summary_data = [
            ("导出时间", summary['export_time']),
            ("数据库名称", summary['database_name']),
            ("数据库版本", summary['database_version']),
            ("字符集", db_info.get('charset', '')),
            ("表总数", str(summary['total_tables'])),
            ("字段总数", str(summary['total_columns'])),
            ("索引总数", str(summary['total_indexes']))
        ]
        
        for label, value in summary_data:
            row_cells = table.add_row().cells
            row_cells[0].text = label
            row_cells[1].text = value
        
        # 添加表列表
        doc.add_heading('表列表', level=2)
        
        # 创建表列表
        table_list = doc.add_table(rows=1, cols=4)
        table_list.style = 'Table Grid'
        table_list.alignment = WD_TABLE_ALIGNMENT.CENTER
        
        # 设置表头
        hdr_cells = table_list.rows[0].cells
        headers = ["表名", "表注释", "字段数", "索引数"]
        for i, header in enumerate(headers):
            hdr_cells[i].text = header
            hdr_cells[i].paragraphs[0].runs[0].font.bold = True
            hdr_cells[i].paragraphs[0].runs[0].font.name = '黑体'
        
        # 添加表数据
        for table_info in dict_data.get('tables', []):
            row_cells = table_list.add_row().cells
            row_cells[0].text = table_info['name']
            row_cells[1].text = table_info.get('comment', '')
            row_cells[2].text = str(len(table_info.get('columns', [])))
            row_cells[3].text = str(len(table_info.get('indexes', [])))
    
    def _add_table_section(self, doc: Document, table: Dict):
        """添加表结构章节"""
        # 表标题
        table_name = table['name']
        doc.add_heading(f'表: {table_name}', level=1)
        
        # 表注释
        if table.get('comment'):
            p = doc.add_paragraph()
            p.add_run('表注释: ').font.bold = True
            p.add_run(table['comment'])
        
        # 字段信息
        doc.add_heading('字段信息', level=2)
        
        # 创建字段表格
        columns = table.get('columns', [])
        if columns:
            field_table = doc.add_table(rows=1, cols=8)
            field_table.style = 'Table Grid'
            field_table.alignment = WD_TABLE_ALIGNMENT.CENTER
            
            # 设置表头
            hdr_cells = field_table.rows[0].cells
            headers = ["字段名", "数据类型", "长度", "精度", "小数位", "是否为空", "默认值", "字段注释"]
            for i, header in enumerate(headers):
                hdr_cells[i].text = header
                hdr_cells[i].paragraphs[0].runs[0].font.bold = True
                hdr_cells[i].paragraphs[0].runs[0].font.name = '黑体'
            
            # 添加字段数据
            for column in columns:
                row_cells = field_table.add_row().cells
                row_cells[0].text = column['name']
                row_cells[1].text = column['type_display']
                row_cells[2].text = str(column.get('length', ''))
                row_cells[3].text = str(column.get('precision', ''))
                row_cells[4].text = str(column.get('scale', ''))
                row_cells[5].text = "是" if column['nullable'] else "否"
                row_cells[6].text = str(column.get('default', ''))
                row_cells[7].text = column.get('comment', '')
        
        # 索引信息
        indexes = table.get('indexes', [])
        if indexes:
            doc.add_heading('索引信息', level=2)
            
            # 创建索引表格
            index_table = doc.add_table(rows=1, cols=4)
            index_table.style = 'Table Grid'
            index_table.alignment = WD_TABLE_ALIGNMENT.CENTER
            
            # 设置表头
            hdr_cells = index_table.rows[0].cells
            headers = ["索引名", "索引类型", "是否唯一", "字段列表"]
            for i, header in enumerate(headers):
                hdr_cells[i].text = header
                hdr_cells[i].paragraphs[0].runs[0].font.bold = True
                hdr_cells[i].paragraphs[0].runs[0].font.name = '黑体'
            
            # 添加索引数据
            for index in indexes:
                row_cells = index_table.add_row().cells
                row_cells[0].text = index['name']
                row_cells[1].text = index['type']
                row_cells[2].text = "是" if index['unique'] else "否"
                row_cells[3].text = ', '.join(index['columns'])
        
        # 添加分页符（除了最后一个表）
        doc.add_page_break()
